package form

import (
	"github.com/mojocn/base64Captcha"
	"github.com/thedevsaddam/govalidator"
)

type Login struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Code     string `json:"code"`
	CodeId   string `json:"code_id"`
}

// ValidateLoginForm 验证表单，返回 errs 长度等于零即通过
func ValidateLoginForm(data Login) map[string][]string {

	// 1. 定制认证规则
	rules := govalidator.MapData{
		"username": []string{"required", "min:2", "max:40"},
		"password": []string{"required", "min:6", "max:40"},
		"code":     []string{"required"},
	}

	// 2. 定制错误消息
	messages := govalidator.MapData{
		"username": []string{
			"required:用户名为必填项",
			"min:长度需大于 2",
			"max:长度需小于 40",
		},
		"password": []string{
			"required:密码为必填项",
			"min:长度需大于 6",
			"max:长度需小于 40",
		},
		"code": []string{
			"required:验证码为必填项",
		},
	}

	// 3. 配置初始化
	opts := govalidator.Options{
		Data:  &data,
		Rules: rules,
		//	TagIdentifier: "valid", // 模型中的 Struct 标签标识符
		Messages: messages,
	}

	// 4. 开始验证
	var errs = govalidator.New(opts).ValidateStruct()
	if len(data.Code) > 0 && base64Captcha.VerifyCaptcha(data.CodeId, data.Code) == false {
		errs["code"] = append(errs["code"], "验证码验证失败")
	}
	return errs
}
